import type { TableConfig } from '@/components/DynamicTable/types';

/**
 * 解析字段配置（处理字符串格式） 根据用户管理来做最底版本
 */
function parseFields(fields: any): any[] {
  if (typeof fields === 'string') {
    try {
      fields = JSON.parse(fields);
    } catch (e) {
      console.error('解析字段失败:', e);
      return [];
    }
  }
  
  if (!Array.isArray(fields)) {
    if (fields && typeof fields === 'object') {
      return Object.values(fields);
    }
    return [];
  }
  
  return fields;
}

/**
 * 转换旧格式的选项配置为新格式
 */
function transformOptionsConfig(field: any, section: 'form' | 'search' | 'table'): any {
  const sectionConfig = field[section];
  if (!sectionConfig) return null;

  // 如果已经有 optionsConfig，检查并规范化
  if (sectionConfig.optionsConfig) {
    const optionsConfig = sectionConfig.optionsConfig;
    
    // 如果是 API 类型，确保使用 apiUrl 字段
    if (optionsConfig.source === 'api') {
      return {
        ...optionsConfig,
        apiUrl: optionsConfig.apiUrl || optionsConfig.apiPath, // 兼容 apiPath
        labelField: optionsConfig.labelField || 'name',
        valueField: optionsConfig.valueField || 'id',
        labelTemplate: optionsConfig.labelTemplate, // 保留标签模板
      };
    }
    
    // 字典类型直接返回
    if (optionsConfig.source === 'dictionary') {
      return optionsConfig;
    }
    
    // 静态选项直接返回
    if (optionsConfig.source === 'static') {
      return optionsConfig;
    }
  }

  // 转换旧格式的 API 选项配置
  if (sectionConfig.optionsSource === 'api' && sectionConfig.optionsApi) {
    return {
      source: 'api',
      apiUrl: sectionConfig.optionsApi,
      labelField: sectionConfig.optionsLabelField || 'name',
      valueField: sectionConfig.optionsValueField || 'id',
    };
  }

  // 状态字段使用字典
  if (field.key === 'status' && !sectionConfig.optionsConfig) {
    return {
      source: 'dictionary',
      dictionaryCode: 'user_status',
    };
  }

  return null;
}

/**
 * 转换字段配置
 */
function transformField(field: any): any {
  const newField = { ...field };

  // 转换表单配置
  if (field.form) {
    const formOptionsConfig = transformOptionsConfig(field, 'form');
    if (formOptionsConfig) {
      newField.form = {
        ...field.form,
        optionsConfig: formOptionsConfig,
      };
      // 删除旧字段
      delete newField.form.optionsSource;
      delete newField.form.optionsApi;
      delete newField.form.optionsLabelField;
      delete newField.form.optionsValueField;
    }
  }

  // 转换搜索配置
  if (field.search) {
    const searchOptionsConfig = transformOptionsConfig(field, 'search');
    if (searchOptionsConfig) {
      newField.search = {
        ...field.search,
        optionsConfig: searchOptionsConfig,
      };
      // 删除旧字段
      delete newField.search.optionsSource;
      delete newField.search.optionsApi;
      delete newField.search.optionsLabelField;
      delete newField.search.optionsValueField;
    }
  }

  // 转换表格配置
  if (field.table) {
    const tableOptionsConfig = transformOptionsConfig(field, 'table');
    if (tableOptionsConfig) {
      newField.table = {
        ...field.table,
        optionsConfig: tableOptionsConfig,
      };
    }
    // 状态字段默认使用字典
    else if (field.key === 'status' && !field.table.optionsConfig) {
      newField.table = {
        ...field.table,
        optionsConfig: {
          source: 'dictionary',
          dictionaryCode: 'user_status',
        },
      };
    }
  }

  return newField;
}

/**
 * 转换表格配置记录为表格配置
 */
export function transformTableConfig(configRecord: any): TableConfig {
  const fields = parseFields(configRecord.fields);
  const transformedFields = fields.map(transformField);

  return {
    name: configRecord.name || '用户管理',
    description: configRecord.description,
    fields: transformedFields,
    actions: configRecord.actions,
    tableProps: configRecord.tableProps,
    permissions: configRecord.permissions,
  };
}

